<template>
  <div class="app-container home">
    <!-- 顶部操作区 - 修改为更适合移动端的布局 -->
    <el-row class="control-panel">
      <el-col :span="24">
        <el-card>
          <div class="current-number">
            <span>当前用户：</span>
            <el-tag :type="currentProcessing.status ? 'success' : 'warning'" size="small" class="mobile-tag">
              {{ currentProcessing.number || '--' }} ({{ currentProcessing.status || '空闲' }})
            </el-tag>
          </div>
          <div class="action-buttons">
            <el-button-group class="mobile-button-group">
              <el-button type="primary" size="small" @click="callNext">叫号</el-button>
              <el-button size="small" @click="skipCurrent">跳过</el-button>
              <el-button size="small" @click="openAddDialog">加号</el-button>
              <el-button size="small" @click="openBatchAddDialog">批量加号</el-button>
              <el-button type="danger" size="small" @click="resetQueue">清空</el-button>
            </el-button-group>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 号码队列展示区 - 添加移动端滚动容器 -->
    <el-row class="queue-display">
      <el-col :span="24">
        <el-card header="排队列表" class="mobile-card">
          <div class="table-container">
            <el-table :data="queueData" border style="width: 100%" :row-class-name="tableRowClassName"
              :max-height="tableHeight">
              <el-table-column prop="username" label="用户名" width="120" />
              <el-table-column prop="createTime" label="添加时间" width="180" />
              <el-table-column prop="state" label="状态" width="120">
                <template #default="{ row }">
                  <el-tag :type="getStatusTagType(row.state)" size="small">
                    {{ row.state }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 加号对话框 - 添加移动端样式 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="90%" top="5vh" custom-class="mobile-dialog"
      :before-close="handleClose">
      <el-form :model="newNumberForm" label-width="80px">
        <el-form-item label="用户名" required>
          <el-input v-model="newNumberForm.targetName" placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取消</el-button>
        <el-button type="primary" @click="confirmAdd" size="small">确定</el-button>
      </div>
    </el-dialog>

    <!-- 批量添加对话框 - 添加移动端样式 -->
    <el-dialog title="批量添加" :visible.sync="batchDialogVisible" width="90%" top="5vh" custom-class="mobile-dialog">
      <el-form :model="batchForm" label-width="80px">
        <el-form-item label="用户列表" required>
          <el-input type="textarea" :rows="3" v-model="batchForm.userList" placeholder="请输入用户名，多个用户用换行或逗号分隔"></el-input>
          <div class="tip">提示：每行一个用户名，或用逗号分隔</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchDialogVisible = false" size="small">取消</el-button>
        <el-button type="primary" @click="confirmBatchAdd" size="small">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getQueueList, addQueue, callQueue, addQueueBatch, resetQueue } from '@/api/cd/queue'
import store from '@/store'

export default {
  data() {
    //const loginUser = store?.getters?.name || '';
    //固定为admin
    const loginUser = 'admin';
    return {
      queueData: [],
      currentNumber: null,
      currentStatus: '',
      currentLoginUser: loginUser,
      dialogVisible: false,
      batchDialogVisible: false,
      newNumberForm: {
        organiser: loginUser,
        targetName: ''
      },
      batchForm: {
        organiser: loginUser,
        userList: ''
      },
      tableHeight: 300 // 初始表格高度
    }
  },
  computed: {
    currentProcessing() {
      const processingItem = this.queueData.find(item => item.state === '进行中');
      return {
        number: processingItem?.username || null,
        status: processingItem?.state || ''
      };
    },
    hasProcessing() {
      return this.queueData.some(item => item.state === '等待中')
    }
  },
  created() {
    this.fetchQueueData();
    this.calculateTableHeight();
    window.addEventListener('resize', this.calculateTableHeight);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeight);
  },
  methods: {
    // 计算表格高度
    calculateTableHeight() {
      const windowHeight = window.innerHeight;
      // 根据窗口高度动态计算表格高度
      this.tableHeight = windowHeight * 0.5; // 占据屏幕50%高度
    },
    // 获取状态标签类型
    getStatusTagType(state) {
      const statusMap = {
        '已完成': 'success',
        '进行中': 'danger',
        '跳过': 'info',
        '已取消': 'info',
        '等待中': ''
      };
      return statusMap[state] || '';
    },
    //进行中高亮显示
    tableRowClassName({ row }) {
      if (row.state === '进行中') {
        return 'highlight-row';
      }
      return '';
    },
    fetchQueueData() {
      const queryParams = { organiser: this.currentLoginUser };
      getQueueList(queryParams).then(response => {
        this.queueData = response.data
      });
    },
    callNext() {
      const queryParams = { organiser: this.currentLoginUser, mode: '已完成' };
      callQueue(queryParams).then(response => {
        this.queueData = response.data
        this.$message.success('叫号成功')
      });
    },
    skipCurrent() {
      const queryParams = { organiser: this.currentLoginUser, mode: '跳过' };
      callQueue(queryParams).then(response => {
        this.queueData = response.data
        this.$message.success('跳过成功')
      });
    },
    async resetQueue() {
      try {
        await this.$confirm('确定要重置队列吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const res = await resetQueue({ organiser: this.currentLoginUser })
        if (res.code === 200) {
          this.$message.success('重置成功')
          this.fetchQueueData()
        }
      } catch (error) {
        console.error(error)
      }
    },
    // 打开对话框的方法
    openAddDialog() {
      this.dialogVisible = true
      this.newNumberForm.targetName = '' // 清空表单
    },

    // 关闭对话框的处理
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },

    // 确认添加
    confirmAdd() {
      if (!this.newNumberForm.targetName.trim()) {
        this.$message.warning('请输入用户名')
        return
      }

      const queryParams = { ...this.newNumberForm }
      addQueue(queryParams).then(response => {
        this.$message.success('添加成功')
        this.dialogVisible = false
        this.queueData = response.data
      }).catch(error => {
      })
    },
    // 打开批量添加对话框
    openBatchAddDialog() {
      this.batchDialogVisible = true;
      this.batchForm.userList = '';
    },

    // 解析用户输入
    parseUserList(text) {
      if (!text.trim()) return '';
      // 支持换行和逗号分隔，最终输出逗号分隔的字符串
      return text.split(/[\n,，]/)
        .map(name => name.trim())
        .filter(name => name.length > 0)
        .join(','); // 将数组用逗号连接成字符串
    },

    // 确认批量添加
    confirmBatchAdd() {
      const targetNames = this.parseUserList(this.batchForm.userList);
      if (targetNames.length === 0) {
        this.$message.warning('请输入至少一个用户名');
        return;
      }

      const queryParams = {
        organiser: this.batchForm.organiser,
        targetNames: targetNames
      };

      addQueueBatch(queryParams).then(response => {
        //this.$message.success(`成功添加 ${targetNames.length} 个用户`);
        this.batchDialogVisible = false;
        this.queueData = response.data;
      }).catch(error => {
        this.$message.error('添加失败: ' + (error.message || '未知错误'));
      });
    },
  }
}
</script>

<style scoped>
.current-number {
  margin-bottom: 20px;
  font-size: 18px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  text-align: right;
}

/* 排队列表样式优化 */
.queue-display {
  margin-top: 20px;
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表格整体优化 */
.el-table {
  background-color: #f8fafc;
  border-collapse: separate;
  border-spacing: 0;
}

.el-table th {
  background-color: #f1f5f9 !important;
  color: #334155;
}

.el-table tr {
  transition: all 0.3s;
}

.el-table tr:hover {
  background-color: #f1f5f9 !important;
}

/* 高亮进行中的行 */
.el-table /deep/ .highlight-row {
  background-color: #fff1f1 !important;
}

.highlight-row td {
  border-top: 1px solid #fecaca !important;
  border-bottom: 1px solid #fecaca !important;
}

.highlight-row:first-child td {
  border-top: 1px solid #fecaca !important;
}

.highlight-row td:first-child {
  border-left: 1px solid #fecaca !important;
}

.highlight-row td:last-child {
  border-right: 1px solid #fecaca !important;
}

/* 状态标签优化 */
.el-tag--danger {
  background-color: #fee2e2 !important;
  border-color: #fecaca !important;
  color: #dc2626 !important;
  font-weight: bold;
}

/* 移动端排队列表 */
/* 移动端适配样式 */
@media screen and (max-width: 768px) {
  .app-container {
    padding: 10px;
  }

  /* 当前用户信息 */
  .current-number {
    font-size: 14px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .mobile-tag {
    margin-left: 5px;
    font-size: 12px;
    padding: 0 5px;
    height: 24px;
    line-height: 22px;
  }

  /* 按钮组 */
  .action-buttons {
    display: flex;
    overflow-x: auto;
    padding-bottom: 5px;
  }

  .mobile-button-group {
    display: flex;
    flex-wrap: nowrap;
    gap: 5px;
  }

  .mobile-button-group .el-button {
    flex: 1;
    min-width: 60px;
    padding: 8px 5px;
    font-size: 12px;
  }

  /* 卡片样式 */
  .mobile-card {
    margin-top: 10px;
  }

  .mobile-card>>>.el-card__header {
    padding: 10px 15px;
    font-size: 14px;
  }

  .mobile-card>>>.el-card__body {
    padding: 10px;
  }

  /* 表格容器 */
  .table-container {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
  }

  /* 表格样式 */
  .el-table {
    font-size: 12px;
    min-width: 600px;
    /* 保证表格最小宽度，使其可以横向滚动 */
  }

  .el-table th,
  .el-table td {
    padding: 8px 5px;
  }

  .el-table-column {
    min-width: 80px;
  }

  /* 状态标签 */
  .el-tag {
    font-size: 10px;
    padding: 0 5px;
    height: 20px;
    line-height: 18px;
  }

  /* 高亮行 */
  .highlight-row td {
    border-top: 1px solid #fecaca !important;
    border-bottom: 1px solid #fecaca !important;
  }
}

/* 对话框全局样式 */
.mobile-dialog {
  border-radius: 8px;
}

.mobile-dialog>>>.el-dialog__header {
  padding: 15px 20px 10px;
}

.mobile-dialog>>>.el-dialog__body {
  padding: 15px 20px;
}

.mobile-dialog>>>.el-dialog__footer {
  padding: 10px 20px 15px;
}

.mobile-dialog>>>.el-form-item {
  margin-bottom: 15px;
}

.mobile-dialog>>>.el-form-item__label {
  font-size: 14px;
  line-height: 1.5;
}

.mobile-dialog>>>.el-input__inner {
  height: 36px;
  line-height: 36px;
}

.mobile-dialog>>>.el-textarea__inner {
  min-height: 80px !important;
}

/* 提示文字 */
.tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

/* 对话框按钮 */
.dialog-footer .el-button {
  padding: 8px 15px;
  font-size: 13px;
}
</style>